const cityAreaId = new Map()
  .set(11, '北京')
  .set(12, '天津')
  .set(13, '河北')
  .set(14, '山西')
  .set(15, '内蒙古')
  .set(21, '辽宁')
  .set(22, '吉林')
  .set(23, '黑龙江')
  .set(31, '上海')
  .set(32, '江苏')
  .set(33, '浙江')
  .set(34, '安徽')
  .set(35, '福建')
  .set(36, '江西')
  .set(37, '山东')
  .set(41, '河南')
  .set(42, '湖北')
  .set(43, '湖南')
  .set(44, '广东')
  .set(45, '广西')
  .set(46, '海南')
  .set(50, '重庆')
  .set(51, '四川')
  .set(52, '贵州')
  .set(53, '云南')
  .set(54, '西藏')
  .set(61, '陕西')
  .set(62, '甘肃')
  .set(63, '青海')
  .set(64, '宁夏')
  .set(65, '新疆')
  .set(71, '台湾')
  .set(81, '香港')
  .set(82, '澳门')
  .set(91, '国外');

function checkIdNumberExist(param: string) {
  let sum = 0;
  const weight = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
  const validate = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
  for (let i = 0; i < param.length - 1; i++) {
    sum += Number(param.charAt(i)) * weight[i];
  }
  const mode = sum % 11;

  if (param.charAt(param.length - 1) !== validate[mode]) return false;
  return true;
}

export function verifyId(param: string) {
  if (!/^\d{17}(\d|x)$/i.test(param)) return { enable: false, message: '身份证长度或格式有误' };
  if (!cityAreaId.has(parseInt(param.substr(0, 2))))
    return { enable: false, message: '身份证地区非法' };
  const birthday =
    param.substr(6, 4) + '-' + Number(param.substr(10, 2)) + '-' + Number(param.substr(12, 2));
  const date = new Date(birthday);
  if (birthday !== date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate())
    return { enable: false, message: '出生日期不符合日历日期' };
  const ifValid = checkIdNumberExist(param);
  if (ifValid) return { enable: true, message: 'success' };
  return { enable: false, message: '校验失败，请输入真实正确的身份证' };
}
